package com.canal.admin.handler;

import com.canal.admin.service.UserTokenService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.canal.admin.entity.TokenBasedAuthentication;
import com.canal.admin.response.Result;
import com.canal.admin.response.ResultUtil;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author Administrator
 * @description
 * @date 2019年03月17 15:47
 */
public class LogoutClearTokenHandler implements LogoutHandler {

    private UserTokenService tokenService;

    public LogoutClearTokenHandler(UserTokenService tokenService) {
        this.tokenService = tokenService;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        Result result = null;
        if(authentication == null) {
            result = ResultUtil.makeFailure(HttpStatus.UNAUTHORIZED.value(),"未登陆，无需注销");
        }
        if(authentication instanceof TokenBasedAuthentication) {
            String token = ((TokenBasedAuthentication)authentication).getToken();
            tokenService.clearToken(token);
            result = ResultUtil.makeSuccess("注销成功");
        }

        ObjectMapper mapper = new ObjectMapper();
        try {
            String resultJsonStr = mapper.writeValueAsString(result);
            response.setContentType("application/json;charset=utf8");
            PrintWriter writer = response.getWriter();
            writer.write(resultJsonStr);
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
